﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Net;
using Demo.Model;
using System.IO;
using System.Threading;

namespace Demo.Site
{
    public class SiteGuangDong : SiteBase
    {
        private string entNo = string.Empty;
        private string entType = string.Empty;
        private string regOrg = string.Empty;

        public SiteGuangDong()
        {
            base.MyWebAddress = "http://gsxt.gdgs.gov.cn/";
            base.InputValidateCode += new EventHandler<InputValidateCodeEventArgs>(SiteGuangDong_InputValidateCode);
        }

        /// <summary>
        /// 验证码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SiteGuangDong_InputValidateCode(object sender, InputValidateCodeEventArgs e)
        {
            e.ValidateCode = InputValidateCodeForm.Show(e.ValidateCodeImage);
        }

        protected override bool CheckResult(string html)
        {
            return true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="searchCondition"></param>
        /// <param name="validateCode"></param>
        /// <returns></returns>
        protected override HttpWebRequest CreateSearchRequest(string searchCondition, string validateCode)
        {
            if (string.IsNullOrEmpty(searchCondition))
                throw new ArgumentNullException("搜索条件不允许为空！");
            string data = string.Format("textfield={0}&code={1}", searchCondition, validateCode);
            byte[] bytes = Encoding.UTF8.GetBytes(data);
            HttpWebRequest request = base.CreatePostRequest("{0}CheckEntContext/showInfo.html");
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0";
            request.Accept = "Accept: text/html,application/xhtml+xml,application/xml,*/*";
            request.Referer = base.MyWebAddress;
            request.Headers.Add("Accept-Language", "zh-cn");
            request.Headers.Add("Accept-Encoding", "gzip, deflate");
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = bytes.Length;
            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(bytes, 0, bytes.Length);
            }
            return request;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="searchCondition"></param>
        /// <param name="validateCode"></param>
        /// <returns></returns>
        protected HttpWebRequest CreateCheckCodeRequest(string searchCondition, string validateCode)
        {
            if (string.IsNullOrEmpty(searchCondition))
                throw new ArgumentNullException("搜索条件不允许为空！");
            string data = string.Format("textfield={0}&code={1}", searchCondition, validateCode);
            byte[] bytes = Encoding.UTF8.GetBytes(data);
            HttpWebRequest request = base.CreatePostRequest("{0}CheckEntContext/checkCode.html");
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0";
            request.Accept = "Accept: text/html,application/xhtml+xml,application/xml,*/*";
            request.Referer = base.MyWebAddress;
            request.Headers.Add("Accept-Language", "zh-cn");
            request.Headers.Add("Accept-Encoding", "gzip, deflate");
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = bytes.Length;
            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(bytes, 0, bytes.Length);
            }
            return request;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        protected override Image ReadCode()
        {
            Image image = null;
            HttpWebRequest request = base.CreateGetRequest(
                string.Format("{{0}}verify.html?random={0}", new Random().NextDouble()));
            request.Accept = "text/html,application/xhtml+xml,application/xml,*/*";
            request.Headers.Add("Accept-Language", "zh-cn");
            request.Headers.Add("Accept-Encoding", "gzip, deflate");

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                base.Cookie.Add(response.Cookies);
                image = base.ReadImageStream(response);
            }
            return image;
        }
        /// <summary>
        /// 
        /// </summary>
        protected override void ReadInitPage()
        {
            HttpWebRequest request = base.CreateGetRequest(
                string.Format("{{0}}verify.html?random={0}", new Random().NextDouble()));
            request.Accept = "text/html,application/xhtml+xml,application/xml,*/*";
            request.Headers.Add("Accept-Language", "zh-cn");
            request.Headers.Add("Accept-Encoding", "gzip, deflate");

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                base.Cookie.Add(response.Cookies);
            }

        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        protected override void ReadDetailInitPage(Company company)
        {
            HttpWebRequest request = null;
            if (company.RedirectUrl.Contains("http:"))
                request = base.CreateGetRequest(company.RedirectUrl);
            else
                request = base.CreateGetRequest(string.Format("{{0}}{0}", company.RedirectUrl));
            request.Accept = "text/html,application/xhtml+xml,application/xml,*/*";
            request.Headers.Add("Accept-Language", "zh-cn");
            request.Headers.Add("Accept-Encoding", "gzip, deflate");
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                base.Cookie.Add(response.Cookies);
                string html = base.ReadStream(response, Encoding.Default);
                this.entNo = base.GetRegValue("name=\"entNo\" value=\"(?<BUHUO>.*?)\">", html);
                this.entType = base.GetRegValue("name=\"entType\" value=\"(?<BUHUO>.*?)\">", html);
                this.regOrg = base.GetRegValue("name=\"regOrg\" value=\"(?<BUHUO>.*?)\">", html);
                if (html.Contains("togo('2')"))
                    company.IsPrivateBuilid = false;
                else
                    company.IsPrivateBuilid = true;

            }

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="searchCondition"></param>
        /// <param name="validateCode"></param>
        /// <param name="searchCallBack"></param>
        protected override void BeginComitSearch(string searchCondition, string validateCode, Action<SiteBase> searchCallBack)
        {
            HttpWebRequest checkRequest = this.CreateCheckCodeRequest(searchCondition, validateCode);
            try
            {
                using (HttpWebResponse response = (HttpWebResponse)checkRequest.GetResponse())
                {
                    string result = base.ReadStream(response, Encoding.UTF8);
                    if (result.Contains("\"flag\":\"1\""))
                    {
                        #region MyRegion
                        HttpWebRequest searchRequest = this.CreateSearchRequest(searchCondition, validateCode);
                        if (searchRequest != null)
                        {
                            object[] asyncResults = new object[] { searchRequest, searchCallBack };
                            searchRequest.BeginGetResponse(new AsyncCallback(base.EndSearchRequest), asyncResults);
                            WaitCallback callBack = delegate(object obj)
                            {
                                Thread.Sleep(this.WebTimeOut);
                                HttpWebRequest request = obj as HttpWebRequest;
                                if (obj != null)
                                {
                                    try
                                    {
                                        request.Abort();
                                    }
                                    catch
                                    {
                                    }
                                }
                            };
                            ThreadPool.QueueUserWorkItem(callBack, searchRequest);
                        }
                        else
                        {
                            searchCallBack(this);
                        }
                        #endregion
                    }
                    else
                    {
                        string[] arrayStrs = result.Split(new string[] { "\"tip\":" }, StringSplitOptions.RemoveEmptyEntries);
                        if (arrayStrs.Length > 1)
                            throw new ArgumentException(arrayStrs[1]);
                    }
                }
            }
            finally
            {
                checkRequest.Abort();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="company"></param>
        /// <param name="companyDetail"></param>
        /// <param name="callBack"></param>
        protected override void BeginReadDetail(Company company, CompanyDetail companyDetail, Action<Company> callBack)
        {

        }


        protected override void ReadDJXX(string html)
        {

        }

        protected override void ReadBAXX(string html)
        {

        }

        protected override void ReadXZCFXX(string html)
        {

        }
    }
}
